package cn.xzz.findactivityfile;

import com.intellij.notification.Notification;
import com.intellij.notification.NotificationGroup;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import org.jetbrains.android.sdk.AndroidSdkUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.InputStream;

public class FindCurrentActivity extends AnAction {

    private static final String FIND_ACTIVITY_TITLE = "获取当前的Activity";
    private static final NotificationGroup NOTIFICATION_GROUP =
            NotificationGroup.balloonGroup(FIND_ACTIVITY_TITLE);
    private String activityNameReal;
    private String adbPath;

    @Override
    public void actionPerformed(AnActionEvent e) {
        adbPath = getAdbPath(e.getProject());
        if (isADBInstalled() && !StringUtils.isEmpty(adbPath)) {
            launchADBFindCurrentActivity(e);
        } else {
            showNotification("adb not found in your environment, please check Android SDK installation and setup, and confirm that adb is available from commandline.", NotificationType.ERROR);
        }
    }

    private void launchADBFindCurrentActivity(AnActionEvent e) {

        if (OSValidator.isMac() || OSValidator.isUnix()) {
            String[] command = new String[]{
                    "/bin/sh",
                    "-c",
                    "cd / && " + adbPath + " shell dumpsys window | grep mCurrentFocus"
            };

            getActivityName(command);
        } else if (OSValidator.isWindows()) {
            String[] command = new String[]{
                    "cmd.exe",
                    "/c",
                    "cd / && " + adbPath + " shell dumpsys window | findstr mCurrentFocus"
            };

            getActivityName(command);
        }
    }

    private void getActivityName(String[] command) {
        try {
            Process process = Runtime.getRuntime().exec(command, null);
            InputStream inputStream = process.getInputStream();
            byte[] bytes = new byte[2048];

            inputStream.read(bytes);
            inputStream.close();
            String activityInfo = new String(bytes).trim();
            String[] split = activityInfo.split(" ");
            //第三个字符串为类名，去掉最后的“}”
            String activityName = split[2].substring(0, split[2].length() - 1);

            String[] names = activityName.split("/");
            if (2 == names.length) {
                if (names[1].startsWith(".")) {
                    activityNameReal = names[0] + names[1];
                } else {
                    activityNameReal = names[1];
                }
                setClipboardString(activityNameReal);

                int action = JOptionPane.showConfirmDialog(null, activityNameReal + "\n类名已复制到系统剪切板，请用快捷键（Ctrl + N）查找，\n或者菜单栏\"Navigate\"->\"Class...\"查找。\n点击下面的按钮，将打开搜索class的窗口，\n如果没有打开窗口，请参照上面的步骤自行打开。", FIND_ACTIVITY_TITLE, JOptionPane.DEFAULT_OPTION);

                if (JOptionPane.YES_OPTION == action) {
                    try {
                        Robot robot = new Robot();
                        robot.keyPress(KeyEvent.VK_CONTROL);
                        robot.keyPress(KeyEvent.VK_N);
                        robot.keyRelease(KeyEvent.VK_CONTROL);
                        robot.keyRelease(KeyEvent.VK_N);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            } else {
                showNotification("Activity不能发现", NotificationType.ERROR);
            }
        } catch (Exception e1) {
            e1.printStackTrace();
            showNotification("程序执行出错，可能手机没有连接", NotificationType.ERROR);
        }
    }

    /**
     * 把文本设置到剪贴板（复制）
     */
    public static void setClipboardString(String text) {
        // 获取系统剪贴板
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        // 封装文本内容
        Transferable trans = new StringSelection(text);
        // 把文本内容设置到系统剪贴板
        clipboard.setContents(trans, null);
    }

    public boolean isADBInstalled() {
        return AndroidSdkUtils.isAndroidSdkAvailable();
    }

    public static void showNotification(final String message,
                                        final NotificationType type) {
        ApplicationManager.getApplication().invokeLater(new Runnable() {
            @Override
            public void run() {
                Notification notification =
                        NOTIFICATION_GROUP.createNotification(FIND_ACTIVITY_TITLE, message, type, null);
                Notifications.Bus.notify(notification);
            }
        });
    }

    private String getAdbPath(Project project) {
        String adbPath = "";
        File adbFile = AndroidSdkUtils.getAdb(project);
        if (adbFile != null) {
            adbPath = adbFile.getAbsolutePath();
        }
        return adbPath;
    }

}
